package com.voice.call.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import voice.voice.call.cache.ConfigSystemCache;
import voice.voice.call.cache.ConfigVosAccountCache;

import com.voice.call.common.Const;
import com.voice.call.common.ConstLang;
import com.voice.call.common.Result;
import com.voice.call.common.ResultEnum;
import com.voice.call.entity.UserInfo;
import com.voice.call.mapper.UserInfoMapper;
import com.voice.call.service.AliSmsService;
import com.voice.call.service.HandlerVosBillService;
import com.voice.call.service.LocalizationSerivce;
import com.voice.call.service.NexmoService;
import com.voice.call.service.VosService;
import com.voice.call.utils.StringUtil;



//缓存清空
@RestController
@RequestMapping("/clear/cache/")
public class ClearCacheController {
	
	private final Logger log = LoggerFactory.getLogger(ClearCacheController.class);
	
	@Resource
	private ConfigSystemCache configSystemCache;
	
	@Resource
	private ConfigVosAccountCache configVosAccountCache;
	
	@Resource
	private HandlerVosBillService handlerVosBillService;
	
	@Resource
	private LocalizationSerivce localizationSerivce;
	

	@Resource
	private AliSmsService aliSmsService;
	
	@Resource
	private VosService  vosService;
	
	@Resource
	private NexmoService nexmoService;
	
	@Resource
	private UserInfoMapper userInfoMapper;
	
	
	private void sendUdp(String serverIp)  {
		
		try {
			 //数据包套接字：相当于码头，专门处理通信数据及进行数据转发设置的
	        DatagramSocket ds=new DatagramSocket();
	        ds.setSoTimeout(10000);//receive数据阻塞等待10s，超过这个时间仍未收到数据说明丢失了
	        String message="Hello Java World!";

	        //数据报包:类似于集装箱，用来存储所有的数据信息
	        DatagramPacket dp=new DatagramPacket(
	                message.getBytes(),   //数据都是已字节数据进行发送的，因此需要将数据进行转换
	                message.length(), //发送数据的长度
	                InetAddress.getByName(serverIp),  //发送数据的源ip地址
	                //InetAddress.getByName("128.1.90.58"),  //发送数据的源ip地址
	                //InetAddress.getByName("120.77.219.131"),  //发送数据的源ip地址
	                23650   //发送数据的端口号
	                );

	        ds.send(dp);  //数据包通过码头DatagramSocket发送出去
	        ds.close();   //数据发送之后关闭通道，减少资源浪费
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error("udp发送发生异常");
		}
		
	}
	
	private  String readLocalFile(String temPath){
		try {
			File file = new File(temPath);
			StringBuilder stringBuilder = new StringBuilder();
			InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file), "UTF-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String lineStr = null;
			while((lineStr = bufferedReader.readLine()) != null){
			stringBuilder.append(lineStr);
			}
			bufferedReader.close();
			inputStreamReader.close();
			//System.out.println("***************stringBuilder.toString()="+stringBuilder.toString());
			String fileContentStr = stringBuilder.toString();
			//System.out.println("************fileContentStr="+fileContentStr);
			return fileContentStr;
		} catch (IOException e) {
		    e.printStackTrace();
		    return null;
		}
		
	}
	
	
	@ResponseBody
	//@ApiVersion(1)
	@RequestMapping(value = "system", method = RequestMethod.GET)
	public Result clearSystemConfig() throws Exception{ 
		
		configSystemCache.reload();
		
		log.info("auto_login = {}",configSystemCache.get(Const.SYSTEM_AUTO_LOGIN));
		
		return new Result();
	}
	
	@ResponseBody
	//@ApiVersion(1)
	@RequestMapping(value = "vos", method = RequestMethod.GET)
	public Result clearVosConfig(){ 
		
		configVosAccountCache.reload();
		
		//log.info("auto_login = {}",configSystemCache.get(Const.SYSTEM_AUTO_LOGIN));
		
		return new Result();
	}
	
	
	@ResponseBody
	@RequestMapping(value = "test", method = RequestMethod.GET)
	public Result testUpdLocal(){
		
		/***
		 
		 {
    "status": 0,
    "status_message": "Success",
    "lookup_outcome": 1,
    "lookup_outcome_message": "Partial success - some fields populated",
    "request_id": "71c8b9d5-ce47-42fb-b718-b9d3c08dcaaf",
    "international_format_number": "8627645342976",
    "national_format_number": "27645342976",
    "country_code": "CN",
    "country_code_iso3": "CHN",
    "country_name": "China (PRC)",
    "country_prefix": "86",
    "request_price": "0.03000000",
    "remaining_balance": "11.2508",
    "current_carrier": {
        "network_code": "CN-FIXED",
        "name": "China (PRC) Landline",
        "country": "CN",
        "network_type": "unknown"
    },
    "original_carrier": {
        "network_code": "CN-FIXED",
        "name": "China (PRC) Landline",
        "country": "CN",
        "network_type": "landline"
    },
    "valid_number": "valid",
    "reachable": "unknown",
    "ported": "not_ported",
    "roaming": {"status": "not_roaming"}
}
		 
		 */
		
		/***
		 
		 
		 {
    "status": 0,
    "status_message": "Success",
    "lookup_outcome": 1,
    "lookup_outcome_message": "Partial success - some fields populated",
    "request_id": "cf0da558-c64e-4483-bf81-9a318b860654",
    "international_format_number": "8617057000128",
    "national_format_number": "170 5700 0128",
    "country_code": "CN",
    "country_code_iso3": "CHN",
    "country_name": "China (PRC)",
    "country_prefix": "86",
    "request_price": "0.03000000",
    "remaining_balance": "11.2808",
    "current_carrier": {
        "network_code": "46000",
        "name": "China Mobile",
        "country": "CN",
        "network_type": "unknown"
    },
    "original_carrier": {
        "network_code": "46001",
        "name": "China Unicom",
        "country": "CN",
        "network_type": "mobile"
    },
    "valid_number": "valid",
    "reachable": "unknown",
    "ported": "not_ported",
    "roaming": {"status": "not_roaming"},
    "ip_warnings": "unknown"
}
		 
		 */
		
		List<UserInfo> list = userInfoMapper.list(null);
		if (list!=null && !list.isEmpty()) {
			
			for (int i=0;i<list.size();i++) {
				
				UserInfo userInfo = list.get(i);
				log.info("当前循环索引:{},id={}",i,userInfo.getId());
				boolean status = nexmoService.checkPhone(userInfo.getPhone(),null);
				if (status) {
					log.info("成功");
				}else {
					
					UserInfo entityInfo = new UserInfo();
					entityInfo.setId(userInfo.getId());
					entityInfo.setStatus(Const.N);
					entityInfo.setMtime(new Date());
					if(userInfoMapper.update(entityInfo)>0){
						log.info("更新状态成功");
					}else {
						log.info("更新状态失败,phone={}",userInfo.getPhone());
					}
					
				}
				
				
			}
			
		}
		
		

		/***
		String[] phoneStrings = {"008618666991181","008613346499213","008618620669680"};
		
		for (String item : phoneStrings) {
			aliSmsService.sendAliWecolmeSms(item);
		}
		**/
		
		//log.info("name ={}",ResultEnum.SUCCESS.toString());
		
		//vosService.getVosAccount("17057000128", "17057000128");
		
		//String msg = localizationSerivce.getLocalForKey("IP_ACCESS_ERROR", "en");
		//ConstLang ctLang =new ConstLang("IP_ACCESS_ERROR", "en");
		//log.info("msg = {}",ctLang.getMsg());
		
		return new Result();
	}
	
	
	
	

}
